package com.unlcn.ils.wms.backend.service.excp.impl;

import cn.huiyunche.commons.constant.QiniuConstant;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.excpBO.ExcpFormBO;
import com.unlcn.ils.wms.backend.dto.excpDTO.ExcpImageDTO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.enums.excp.ExcepTypeEnum;
import com.unlcn.ils.wms.backend.enums.excp.ExcpDealTypeEnum;
import com.unlcn.ils.wms.backend.enums.excp.ExcpStatusEnum;
import com.unlcn.ils.wms.backend.service.excp.ExcpManageService;
import com.unlcn.ils.wms.backend.service.inbound.WmsInboundRepairService;
import com.unlcn.ils.wms.base.dto.ExcpManageDTO;
import com.unlcn.ils.wms.base.dto.ExcpTypeDTO;
import com.unlcn.ils.wms.base.mapper.extmapper.ExcpExtMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundOrderDetailMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundOrderMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundRepairMapper;
import com.unlcn.ils.wms.base.mapper.inspectApp.*;
import com.unlcn.ils.wms.base.mapper.outbound.WmsOutboundTaskMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsInventoryLocationMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsInventoryMapper;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrder;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrderDetail;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundOrderDetailExample;
import com.unlcn.ils.wms.base.model.inbound.WmsInboundRepair;
import com.unlcn.ils.wms.base.model.inspectApp.*;
import com.unlcn.ils.wms.base.model.outbound.WmsOutboundTask;
import com.unlcn.ils.wms.base.model.stock.WmsInventory;
import com.unlcn.ils.wms.base.model.stock.WmsInventoryLocation;
import com.unlcn.ils.wms.base.model.stock.WmsInventoryLocationExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther linbao
 * @Date 2017-11-22
 * 异常信息管理
 */
@Service
public class ExcpManageServiceImpl implements ExcpManageService {

    private Logger logger = LoggerFactory.getLogger(ExcpManageServiceImpl.class);

    private static final String TYPE_DEAL = "DEAL";//处理
    private static final String TYPE_CLOSED = "CLOSED";//关闭

    @Autowired
    private ExcpExtMapper excpExtMapper;//异常描述

    @Autowired
    private WmsInboundOrderMapper wmsInboundOrderMapper;//入库单

    @Autowired
    private WmsOutboundTaskMapper wmsOutboundTaskMapper;//出库任务

    @Autowired
    private TmsInspectExcpMapper tmsInspectExcpMapper;//入库质损异常

    @Autowired
    private TmsInspectComponentMissMapper tmsInspectComponentMissMapper;//入库缺件异常

    @Autowired
    private TmsOutboundInspectExcpMapper tmsOutboundInspectExcpMapper;//出库质损异常

    @Autowired
    private TmsOutboundComponentMissMapper tmsOutboundComponentMissMapper;//出库缺件

    @Autowired
    private TmsInspectExcpTypeMapper tmsInspectExcpTypeMapper;//异常类型

    @Autowired
    private WmsInboundRepairService wmsInboundRepairService;//维修单

    @Autowired
    private WmsInboundRepairMapper wmsInboundRepairMapper;//维修单

    @Autowired
    private WmsInboundOrderDetailMapper wmsInboundOrderDetailMapper;//入库单

    @Autowired
    private WmsInventoryMapper wmsInventoryMapper;//在库库存

    @Autowired
    private WmsInventoryLocationMapper wmsInventoryLocationMapper;//在库库存库位

    /**
     * 异常信息的分页查询
     * <p>
     * 2018-1-30 新需求:异常管理列表查询界面新增车架号/订单号查询
     * </p>
     *
     * @param excpFormBO 参数封装
     * @return 返回值
     */
    @Override
    public Map<String, Object> queryExcpListForPage(ExcpFormBO excpFormBO) {
        logger.info("ExcpManageServiceImpl.queryExcpListForPage param: {}", excpFormBO);
        //校验
        checkParam(excpFormBO, false);
        //获取参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("whCode", excpFormBO.getWhCode());
        if (WarehouseEnum.JM_XY.getWhCode().equals(excpFormBO.getWhCode()) || WarehouseEnum.JM_CS.getWhCode().equals(excpFormBO.getWhCode())) {
            paramMap.put("odStatus", String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue()));
        }
        paramMap.put("delFlag", "1");
        Map<String, Object> commonParamMap = getParamMap(excpFormBO);

        List<ExcpManageDTO> excpManageDTOList = excpExtMapper.queryExcpManageDtoList(paramMap, commonParamMap);
        getExcepDesc(excpManageDTOList, null, null, " , ");

        //分页数据
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(excpFormBO.getPageNo());
        pageVo.setPageSize(excpFormBO.getPageSize());
        pageVo.setTotalRecord(excpExtMapper.countExcpManageDto(paramMap, commonParamMap));

        //返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("page", pageVo);
        resultMap.put("dataList", excpManageDTOList);
        return resultMap;
    }

    /**
     * 异常列表的导出--重庆库
     * <p>
     * 2018-1-29 异常的列表导出
     * </p>
     *
     * @param bo 参数封装
     */
    @Override
    public HSSFWorkbook getImportOutExcel(ExcpFormBO bo) {
        logger.info("ExcpManageServiceImpl.getImportOutExcel param:{}", JSONObject.toJSONString(bo));
        if (Objects.equals(bo, null))
            throw new BusinessException("参数不能为空!");
        if (StringUtils.isBlank(bo.getWhCode()))
            throw new BusinessException("仓库code不能为空!");
        //if (!WhCodeEnum.UNLCN_XN_CQ.getValue().equals(bo.getWhCode()))
        //    throw new BusinessException("该仓库不支持此操作!");

        Map<String, Object> commonMap = getParamMap(bo);
        Map<String, Object> singleMap = Maps.newHashMap();
        singleMap.put("whCode", bo.getWhCode());
        if (WarehouseEnum.JM_XY.getWhCode().equals(bo.getWhCode()) || WarehouseEnum.JM_CS.getWhCode().equals(bo.getWhCode())) {
            singleMap.put("odStatus", String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue()));
        }
        singleMap.put("delFlag", DeleteFlagEnum.NORMAL.getValue());
        List<ExcpManageDTO> excpManageDTOList = excpExtMapper.selectImportData(singleMap, commonMap);
        if (CollectionUtils.isNotEmpty(excpManageDTOList)) {
            getExcepDesc(excpManageDTOList, "(", ")", "、");
            //1.导出excel头
            //订单号 车架号	异常分类	异常类型	异常状态	异常描述	责任方 异常图片	异常发生时间	处理方式	处理结果描述	处理完成时间
            String[] hearders = new String[]{
                    "订单号", "车架号", "异常分类", "异常类型", "异常状态", "异常描述", "验车人", "异常发生时间", "处理方式", "处理结果描述", "处理完成时间"
            };
            //设置值
            return updateExportToExcelForCQ("异常记录数据导出", hearders, excpManageDTOList, "yyyy-MM-dd HH:mm:ss");
        }
        return null;
    }


    /**
     * 异常处理
     */
    @Override
    public void updateToDealExcp(ExcpFormBO excpFormBO) throws Exception {
        logger.info("ExcpManageServiceImpl.updateToDealExcp param: {}", excpFormBO);
        //校验
        checkParam(excpFormBO, true);
        //判断异常类型
        if (StringUtils.isBlank(excpFormBO.getDealType())) {
            throw new BusinessException("异常处理方式不能为空");
        }
        if (StringUtils.isBlank(excpFormBO.getExcpTimestamp())) {
            throw new BusinessException("参数时间戳不能为空");
        }
        queryCheckDate(excpFormBO.getOrderId(), excpFormBO.getExcpType());
        if (StringUtils.isBlank(excpFormBO.getExcpTypeCode())) {
            throw new BusinessException("当前数据缺少异常类型");
        }
        //step-1 校验
        checkDealTypeAndExcpType(excpFormBO.getDealType(), excpFormBO.getExcpTypeCode());

        //step-2 处理异常
        updateToDealOrClosed(excpFormBO, TYPE_DEAL);
    }

    /**
     * 异常关闭
     */
    @Override
    public void updateToCloseExcp(ExcpFormBO excpFormBO) throws Exception {
        logger.info("ExcpManageServiceImpl.updateToCloseExcp param: {}", excpFormBO);
        //校验
        checkParam(excpFormBO, true);
        if (StringUtils.isBlank(excpFormBO.getExcpTimestamp())) {
            throw new BusinessException("参数时间戳不能为空");
        }
        queryCheckDate(excpFormBO.getOrderId(), excpFormBO.getExcpType());
        //关系异常
        updateToDealOrClosed(excpFormBO, TYPE_CLOSED);
    }

    /**
     * 获取异常图片信息
     */
    @Override
    public List<ExcpImageDTO> getExcpImageList(ExcpFormBO excpFormBO) {
        logger.info("ExcpManageServiceImpl.updateToCloseExcp param: {}", excpFormBO);
        //校验
        checkParam(excpFormBO, true);
        List<ExcpImageDTO> imageDTOList = null;
        if (ExcepTypeEnum.IN_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
            //入库异常
            List<ExcpTypeDTO> inboundExcpTypeList = excpExtMapper.getInboundExcpTypeList(excpFormBO.getOrderId(), excpFormBO.getExcpTimestamp());
            imageDTOList = packageImageList(inboundExcpTypeList);
        }
        if (ExcepTypeEnum.OUT_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
            //出库异常
            List<ExcpTypeDTO> outboundExcpTypeList = excpExtMapper.getOutboundExcpTypeList(excpFormBO.getOrderId(), excpFormBO.getExcpTimestamp());
            imageDTOList = packageImageList(outboundExcpTypeList);
        }
        return imageDTOList;
    }

    /**
     * 封装图片信息
     */
    private List<ExcpImageDTO> packageImageList(List<ExcpTypeDTO> dtoList) {
        if (CollectionUtils.isNotEmpty(dtoList)) {
            List<ExcpImageDTO> imageDTOList = new ArrayList<>();
            dtoList.stream()
                    .filter(Objects::nonNull)
                    .forEach(dto -> {
                        ExcpImageDTO imageDTO = new ExcpImageDTO();
                        String desc = dto.getExcpPositionName() + "_" +
                                dto.getExcpBodyName() + "_" +
                                dto.getExcpHurtName();
                        imageDTO.setDesc(desc);
                        if (StringUtils.isNotBlank(dto.getPicKey())) {
                            imageDTO.setImageUrl(QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, dto.getPicKey(), "", null, null));
                        }
                        imageDTOList.add(imageDTO);
                    });
            return imageDTOList;
        }
        return null;
    }


    /**
     * 异常信息描述
     *
     * @param excpManageDTOList 异常列表
     * @param excpLeftSplit     异常描述的左边分割
     * @param excpRightSplit    异常描述的右边分割
     * @param descSplit         异常描述之间的分割
     */
    private void getExcepDesc(List<ExcpManageDTO> excpManageDTOList, String excpLeftSplit, String excpRightSplit, String descSplit) {
        //Long orderId, String type
        if (CollectionUtils.isNotEmpty(excpManageDTOList)) {
            excpManageDTOList.stream()
                    .filter(dto -> dto != null && dto.getOrderId() != null && StringUtils.isNotBlank(dto.getExcpType()))
                    .forEach((ExcpManageDTO dto) -> {
                        if (dto.getOrderId() != null && StringUtils.isNotBlank(dto.getExcpType())) {
                            //单纯的缺件异常
                            if (WmsInspectExcpTypeEnum.TYPE_MISS.getCode().equals(dto.getExcpTypeCode())) {
                                //查询缺件信息
                                if (ExcepTypeEnum.IN_EXCEP.getCode().equals(dto.getExcpType())) {
                                    //入库异常
                                    List<String> inboundMissList = excpExtMapper.getInboundMissList(dto.getOrderId(), dto.getExcpTimestamp());
                                    dto.setExcpDesc(getMissDesc(inboundMissList, excpLeftSplit, excpRightSplit, descSplit));
                                }
                                if (ExcepTypeEnum.OUT_EXCEP.getCode().equals(dto.getExcpType())) {
                                    //出库异常
                                    List<String> outboundMissList = excpExtMapper.getOutboundMissList(dto.getOrderId(), dto.getExcpTimestamp());
                                    dto.setExcpDesc(getMissDesc(outboundMissList, excpLeftSplit, excpRightSplit, descSplit));
                                }
                            } else {
                                //非单纯的缺件异常
                                if (ExcepTypeEnum.IN_EXCEP.getCode().equals(dto.getExcpType())) {
                                    //入库异常
                                    List<ExcpTypeDTO> inboundExcpTypeList = excpExtMapper.getInboundExcpTypeList(dto.getOrderId(), dto.getExcpTimestamp());
                                    dto.setExcpDesc(getDesc(inboundExcpTypeList, excpLeftSplit, excpRightSplit, descSplit));
                                    if (WmsInspectExcpTypeEnum.TYPE_MISS_AND_EXCP.getCode().equals(dto.getExcpTypeCode())
                                            || WmsInspectExcpTypeEnum.TYPE_LOSS_AND_MISS.getCode().equals(dto.getExcpTypeCode())
                                            || WmsInspectExcpTypeEnum.TYPE_LOSS_EXCP_MISS.getCode().equals(dto.getExcpTypeCode())) {

                                        List<String> inboundMissList = excpExtMapper.getInboundMissList(dto.getOrderId(), dto.getExcpTimestamp());
                                        String missDesc = getMissDesc(inboundMissList, excpLeftSplit, excpRightSplit, descSplit);
                                        if (StringUtils.isNotBlank(missDesc) && StringUtils.isNotBlank(dto.getExcpDesc())) {
                                            if (StringUtils.isNotBlank(excpLeftSplit)) {
                                                dto.setExcpDesc(excpLeftSplit + missDesc + excpRightSplit + descSplit + dto.getExcpDesc());
                                            } else {
                                                dto.setExcpDesc(missDesc + ", " + dto.getExcpDesc());
                                            }
                                        }
                                    }
                                }
                                if (ExcepTypeEnum.OUT_EXCEP.getCode().equals(dto.getExcpType())) {
                                    //出库异常
                                    List<ExcpTypeDTO> outboundExcpTypeList = excpExtMapper.getOutboundExcpTypeList(dto.getOrderId(), dto.getExcpTimestamp());
                                    dto.setExcpDesc(getDesc(outboundExcpTypeList, excpLeftSplit, excpRightSplit, descSplit));
                                    if (WmsInspectExcpTypeEnum.TYPE_MISS_AND_EXCP.getCode().equals(dto.getExcpTypeCode())
                                            || WmsInspectExcpTypeEnum.TYPE_LOSS_AND_MISS.getCode().equals(dto.getExcpTypeCode())
                                            || WmsInspectExcpTypeEnum.TYPE_LOSS_EXCP_MISS.getCode().equals(dto.getExcpTypeCode())) {

                                        List<String> outboundMissList = excpExtMapper.getOutboundMissList(dto.getOrderId(), dto.getExcpTimestamp());
                                        String missDesc = getMissDesc(outboundMissList, excpLeftSplit, excpRightSplit, descSplit);
                                        if (StringUtils.isNotBlank(missDesc) && StringUtils.isNotBlank(dto.getExcpDesc())) {
                                            if (StringUtils.isNotBlank(excpLeftSplit)) {
                                                dto.setExcpDesc(excpLeftSplit + missDesc + excpRightSplit + descSplit + dto.getExcpDesc());
                                            } else {
                                                dto.setExcpDesc(missDesc + ", " + dto.getExcpDesc());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
        }
    }

    /**
     * 异常信息拼接
     *
     * @param dtoList        列表
     * @param excpLeftSplit  异常左分割
     * @param excpRightSplit 异常右分割
     * @param descSplit      描述分割
     * @return 返回值
     */
    private String getDesc(List<ExcpTypeDTO> dtoList, String excpLeftSplit, String excpRightSplit, String descSplit) {
        if (CollectionUtils.isNotEmpty(dtoList)) {
            StringBuilder desc = new StringBuilder();
            dtoList.forEach(dto -> {
                if (StringUtils.isNotBlank(excpLeftSplit)) {
                    desc.append(excpLeftSplit);
                }
                desc.append(dto.getExcpPositionName());
                desc.append("_");
                desc.append(dto.getExcpBodyName());
                desc.append("_");
                desc.append(dto.getExcpHurtName());
                if (StringUtils.isNotBlank(excpRightSplit)) {
                    desc.append(excpRightSplit);
                }
                desc.append(descSplit);
            });
            if (StringUtils.isNotBlank(desc.toString())) {
                return desc.substring(0, desc.lastIndexOf(descSplit));
            }
        }
        return null;
    }

    /**
     * 缺件异常描述
     */
    private String getMissDesc(List<String> missExcpList, String excpLeftSplit, String excpRightSplit, String descSplit) {
        if (CollectionUtils.isNotEmpty(missExcpList)) {
            StringBuilder desc = new StringBuilder();
            missExcpList.stream()
                    .filter(StringUtils::isNotBlank)
                    .forEach(missExcp -> {
                        desc.append("缺少");
                        desc.append(missExcp).append(descSplit);
                    });
            if (StringUtils.isNotBlank(desc.toString())) {
                return desc.substring(0, desc.lastIndexOf(descSplit));
            }
        }
        return null;
    }

    /**
     * 校验
     */
    private void checkParam(ExcpFormBO excpFormBO, boolean isUpdate) {
        if (excpFormBO == null) {
            throw new BusinessException("参数不能为空");
        }
        if (isUpdate) {
            if (StringUtils.isBlank(excpFormBO.getExcpType())) {
                throw new BusinessException("异常分类为空");
            }
            if (excpFormBO.getOrderId() == null) {
                throw new BusinessException("未选择数据");
            }
        }
    }

    /**
     * 校验数据是否存在
     */
    private Integer queryCheckDate(Long orderId, String type) {
        if (ExcepTypeEnum.IN_EXCEP.getCode().equals(type)) {
            //入库异常
            WmsInboundOrder order = getInboundOrder(orderId);
            if (order == null) {
                throw new BusinessException("找不到对应的数据");
            }
            return order.getOdInspectExcpType();
        }
        if (ExcepTypeEnum.OUT_EXCEP.getCode().equals(type)) {
            //出库异常
            WmsOutboundTask outboundTask = getOutboundTask(orderId);
            if (outboundTask == null) {
                throw new BusinessException("找不到对应的数据");
            }
            if (StringUtils.isNotBlank(outboundTask.getOtExceptionType())
                    && StringUtils.isNumeric(outboundTask.getOtExceptionType())) {
                return Integer.parseInt(outboundTask.getOtExceptionType());
            }
        }
        //if (ExcepTypeEnum.PREPARE_EXCEP.getCode().equals(type)) {
        //    //备料异常
        //}
        return null;
    }

    /**
     * 获取入库数据
     */
    private WmsInboundOrder getInboundOrder(Long orderId) {
        if (orderId != null) {
            return wmsInboundOrderMapper.selectByPrimaryKey(orderId);
        }
        return null;
    }

    /**
     * 获取出库数据
     */
    private WmsOutboundTask getOutboundTask(Long orderId) {
        if (orderId != null) {
            return wmsOutboundTaskMapper.selectByPrimaryKey(orderId);
        }
        return null;
    }

    /**
     * 根据异常id获取异常类型code
     */
    private String getExcpTypeCode(Integer typeId) {
        if (typeId != null) {
            TmsInspectExcpType tmsInspectExcpType = tmsInspectExcpTypeMapper.selectByPrimaryKey(typeId);
            if (tmsInspectExcpType != null) {
                return tmsInspectExcpType.getTypeCode();
            }
        }
        return null;
    }

    /**
     * 判断异常类型和处理类型的对应
     */
    private void checkDealTypeAndExcpType(String dealType, String excpTypeCode) {
        if (StringUtils.isNotBlank(dealType) && StringUtils.isNotBlank(excpTypeCode)) {

            if (WmsInspectExcpTypeEnum.TYPE_MISS.getCode().equals(excpTypeCode)) {
                //缺件
                if (!String.valueOf(ExcpDealTypeEnum.MISS_FOLLOW.getCode()).equals(dealType)) {
                    throw new BusinessException("缺件异常只可选择缺件跟进");
                }
            } else if (WmsInspectExcpTypeEnum.TYPE_EXCP.getCode().equals(excpTypeCode)) {
                //质损
                if (!String.valueOf(ExcpDealTypeEnum.OUT_WAREHOUSE_REPAIR.getCode()).equals(dealType)
                        && !String.valueOf(ExcpDealTypeEnum.IN_WAREHOUSE_REPAIR.getCode()).equals(dealType)) {
                    throw new BusinessException("质损异常只可选择出库维修或库内维修");
                }
            } else if (WmsInspectExcpTypeEnum.TYPE_MISS_AND_EXCP.getCode().equals(excpTypeCode)) {
                if (!String.valueOf(ExcpDealTypeEnum.MISS_FOLLOW_AND_OUT_WAREHOUSE.getCode()).equals(dealType)
                        && !String.valueOf(ExcpDealTypeEnum.MISS_FOLLOW_AND_IN_WAREHOUSE.getCode()).equals(dealType)) {
                    throw new BusinessException("缺件且质损异常只可选择(缺件跟进、出库维修)或(缺件跟进、库内维修)");
                }
            }
        }
    }

    /**
     * 处理异常
     */
    private void updateToDealOrClosed(ExcpFormBO excpFormBO, String dealOrClosed) throws Exception {
        if (ExcepTypeEnum.IN_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
            //入库异常
            //缺件
            if (WmsInspectExcpTypeEnum.TYPE_MISS.getCode().equals(excpFormBO.getExcpTypeCode())) {
                if (TYPE_DEAL.equals(dealOrClosed)) {
                    //更新异常状态为20
                    updateInMissExcepDealing(excpFormBO);
                } else if (TYPE_CLOSED.equals(dealOrClosed)) {
                    //更新缺件
                    updateInMissExcepClosed(excpFormBO);
                    //更新异常状态为30
                    updateStatusInbound(excpFormBO);
                }
            }
            //质损
            if (WmsInspectExcpTypeEnum.TYPE_EXCP.getCode().equals(excpFormBO.getExcpTypeCode())) {
                if (TYPE_DEAL.equals(dealOrClosed)) {
                    //step-3 生成维修单
                    Long repairId = createRepair(excpFormBO, String.valueOf(WmsRepairInAndOutTypeEnum.INBOUND_REPAIR.getValue()),
                            String.valueOf(WmsRepairInspectPlaceEnum.INBOUND_PLACE.getValue()));
                    updateInExcepDealing(excpFormBO, repairId);
                } else if (TYPE_CLOSED.equals(dealOrClosed)) {
                    //校验维修单状态
                    queryCheckInboundepairStatus(excpFormBO);
                    //更新质损质损异常未已关闭30
                    updateInExcepColsed(excpFormBO);
                    //更新异常状态为30
                    //updateStatusInbound(bo);
                }
            }
            //缺件且质损
            if (WmsInspectExcpTypeEnum.TYPE_MISS_AND_EXCP.getCode().equals(excpFormBO.getExcpTypeCode())) {
                if (TYPE_DEAL.equals(dealOrClosed)) {
                    updateInMissExcepDealing(excpFormBO);
                    //step-3 生成维修单
                    Long repairId = createRepair(excpFormBO, String.valueOf(WmsRepairInAndOutTypeEnum.INBOUND_REPAIR.getValue()),
                            String.valueOf(WmsRepairInspectPlaceEnum.INBOUND_PLACE.getValue()));
                    updateInExcepDealing(excpFormBO, repairId);
                } else if (TYPE_CLOSED.equals(dealOrClosed)) {
                    //校验维修单状态
                    queryCheckInboundepairStatus(excpFormBO);
                    //更新缺件异常状态为已关闭30
                    updateInMissExcepClosed(excpFormBO);
                    updateInExcepColsed(excpFormBO);
                    //更新异常状态为30
                    //updateStatusInbound(bo);
                }
            }
        }
        if (ExcepTypeEnum.OUT_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
            //出库异常
            //缺件
            if (WmsInspectExcpTypeEnum.TYPE_MISS.getCode().equals(excpFormBO.getExcpTypeCode())) {
                if (TYPE_DEAL.equals(dealOrClosed)) {
                    updateOutMissDealing(excpFormBO);
                } else if (TYPE_CLOSED.equals(dealOrClosed)) {
                    updateOutMissClosed(excpFormBO);
                    //更新异常状态为30
                    updateStatusOutbound(excpFormBO);
                }
            }
            //质损
            if (WmsInspectExcpTypeEnum.TYPE_EXCP.getCode().equals(excpFormBO.getExcpTypeCode())) {
                if (TYPE_DEAL.equals(dealOrClosed)) {
                    //step-3 生成维修单
                    Long repairId = createRepair(excpFormBO, String.valueOf(WmsRepairInAndOutTypeEnum.OUTBOUND_REPAIR.getValue()), null);
                    updateOutExcepDealing(excpFormBO, repairId);
                } else if (TYPE_CLOSED.equals(dealOrClosed)) {
                    //校验维修单状态
                    queryCheckOutboundepairStatus(excpFormBO);
                    updateOutExcepClosed(excpFormBO);
                    //更新异常状态为30
                    //updateStatusOutbound(bo);
                }
            }
            //缺件且质损
            if (WmsInspectExcpTypeEnum.TYPE_MISS_AND_EXCP.getCode().equals(excpFormBO.getExcpTypeCode())) {
                if (TYPE_DEAL.equals(dealOrClosed)) {
                    updateOutMissDealing(excpFormBO);
                    //step-3 生成维修单
                    Long repairId = createRepair(excpFormBO, String.valueOf(WmsRepairInAndOutTypeEnum.OUTBOUND_REPAIR.getValue()), null);
                    updateOutExcepDealing(excpFormBO, repairId);
                } else if (TYPE_CLOSED.equals(dealOrClosed)) {
                    //校验维修单状态
                    queryCheckOutboundepairStatus(excpFormBO);
                    //更新缺件异常状态为已关闭
                    updateOutMissClosed(excpFormBO);
                    updateOutExcepClosed(excpFormBO);
                    //更新异常状态为30
                    //updateStatusOutbound(bo);
                }
            }
        }
        //if (ExcepTypeEnum.PREPARE_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
        //备料异常
        //}
    }

    /**
     * 处理入库缺件
     */
    private void updateInMissExcepDealing(ExcpFormBO excpFormBO) {
        TmsInspectComponentMissExample missExample = new TmsInspectComponentMissExample();
        missExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpTimestampEqualTo(excpFormBO.getExcpTimestamp())
                .andExcpStatusEqualTo(ExcpStatusEnum.NOT_DEAL.getCode());
        int count = tmsInspectComponentMissMapper.countByExample(missExample);
        if (count <= 0) {
            throw new BusinessException("非未处理异常不可处理");
        }

        TmsInspectComponentMiss updateMiss = new TmsInspectComponentMiss();
        updateMiss.setGmtUpdate(new Date());
        updateMiss.setDealType(new Byte(excpFormBO.getDealType()));
        updateMiss.setExcpStatus(ExcpStatusEnum.DEALING.getCode());

        tmsInspectComponentMissMapper.updateByExampleSelective(updateMiss, missExample);
    }

    /**
     * 处理入库质损
     */
    private void updateInExcepDealing(ExcpFormBO excpFormBO, Long repairId) {
        TmsInspectExcpExample excpExample = new TmsInspectExcpExample();
        excpExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpTimestampEqualTo(excpFormBO.getExcpTimestamp())
                .andExcpStatusEqualTo(ExcpStatusEnum.NOT_DEAL.getCode());
        int count = tmsInspectExcpMapper.countByExample(excpExample);
        if (count <= 0) {
            throw new BusinessException("非未处理异常不可处理");
        }

        TmsInspectExcp inspectExcp = new TmsInspectExcp();
        inspectExcp.setGmtUpdate(new Date());
        inspectExcp.setDealType(new Byte(excpFormBO.getDealType()));
        inspectExcp.setExcpStatus(ExcpStatusEnum.DEALING.getCode());
        inspectExcp.setExcpRepairId(repairId);//维修单ID

        tmsInspectExcpMapper.updateByExampleSelective(inspectExcp, excpExample);
    }

    /**
     * 处理出库缺件
     */
    private void updateOutMissDealing(ExcpFormBO excpFormBO) {
        TmsOutboundComponentMissExample missExample = new TmsOutboundComponentMissExample();
        missExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpTimestampEqualTo(excpFormBO.getExcpTimestamp())
                .andExcpStatusEqualTo(ExcpStatusEnum.NOT_DEAL.getCode());
        int count = tmsOutboundComponentMissMapper.countByExample(missExample);
        if (count <= 0) {
            throw new BusinessException("非未处理异常不可处理");
        }

        TmsOutboundComponentMiss outboundComponentMiss = new TmsOutboundComponentMiss();
        outboundComponentMiss.setGmtUpdate(new Date());
        outboundComponentMiss.setDealType(new Byte(excpFormBO.getDealType()));
        outboundComponentMiss.setExcpStatus(ExcpStatusEnum.DEALING.getCode());

        tmsOutboundComponentMissMapper.updateByExampleSelective(outboundComponentMiss, missExample);
    }

    /**
     * 处理出库质损
     */
    private void updateOutExcepDealing(ExcpFormBO excpFormBO, Long repairId) {
        TmsOutboundInspectExcpExample excpExample = new TmsOutboundInspectExcpExample();
        excpExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpTimestampEqualTo(excpFormBO.getExcpTimestamp())
                .andExcpStatusEqualTo(ExcpStatusEnum.NOT_DEAL.getCode());
        int count = tmsOutboundInspectExcpMapper.countByExample(excpExample);
        if (count <= 0) {
            throw new BusinessException("非未处理异常不可处理");
        }

        TmsOutboundInspectExcp outboundInspectExcp = new TmsOutboundInspectExcp();
        outboundInspectExcp.setGmtUpdate(new Date());
        outboundInspectExcp.setDealType(new Byte(excpFormBO.getDealType()));
        outboundInspectExcp.setExcpStatus(ExcpStatusEnum.DEALING.getCode());
        outboundInspectExcp.setExcpRepairId(repairId);//维修单ID

        tmsOutboundInspectExcpMapper.updateByExampleSelective(outboundInspectExcp, excpExample);
    }

    /**
     * 关闭入库缺件
     */
    private void updateInMissExcepClosed(ExcpFormBO excpFormBO) {
        TmsInspectComponentMissExample missExample = new TmsInspectComponentMissExample();
        missExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpStatusEqualTo(ExcpStatusEnum.DEALING.getCode());
        int count = tmsInspectComponentMissMapper.countByExample(missExample);
        if (count <= 0) {
            throw new BusinessException("非处理中异常不可关闭");
        }

        TmsInspectComponentMiss updateMiss = new TmsInspectComponentMiss();
        updateMiss.setDealEndTime(new Date());
        updateMiss.setGmtUpdate(new Date());
        updateMiss.setExcpStatus(ExcpStatusEnum.CLOSED.getCode());
        updateMiss.setDealResultDesc(excpFormBO.getDealResultDesc());

        tmsInspectComponentMissMapper.updateByExampleSelective(updateMiss, missExample);
    }

    /**
     * 关闭入库质损
     */
    private void updateInExcepColsed(ExcpFormBO excpFormBO) {
        TmsInspectExcpExample excpExample = new TmsInspectExcpExample();
        excpExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpStatusEqualTo(ExcpStatusEnum.DEALING.getCode());
        int count = tmsInspectExcpMapper.countByExample(excpExample);
        if (count <= 0) {
            throw new BusinessException("非处理中异常不可关闭");
        }

        TmsInspectExcp inspectExcp = new TmsInspectExcp();
        inspectExcp.setGmtUpdate(new Date());
        inspectExcp.setExcpStatus(ExcpStatusEnum.CLOSED.getCode());
        inspectExcp.setDealResultDesc(excpFormBO.getDealResultDesc());
        inspectExcp.setDealEndTime(new Date());

        tmsInspectExcpMapper.updateByExampleSelective(inspectExcp, excpExample);
    }

    /**
     * 关系出库缺件
     */
    private void updateOutMissClosed(ExcpFormBO excpFormBO) {
        TmsOutboundComponentMissExample missExample = new TmsOutboundComponentMissExample();
        missExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpStatusEqualTo(ExcpStatusEnum.DEALING.getCode());
        int count = tmsOutboundComponentMissMapper.countByExample(missExample);
        if (count <= 0) {
            throw new BusinessException("非处理中异常不可关闭");
        }

        TmsOutboundComponentMiss outboundComponentMiss = new TmsOutboundComponentMiss();
        outboundComponentMiss.setGmtUpdate(new Date());
        outboundComponentMiss.setDealEndTime(new Date());
        outboundComponentMiss.setExcpStatus(ExcpStatusEnum.CLOSED.getCode());//更新状态已关闭
        outboundComponentMiss.setDealResultDesc(excpFormBO.getDealResultDesc());

        tmsOutboundComponentMissMapper.updateByExampleSelective(outboundComponentMiss, missExample);
    }

    /**
     * 关系出库质损
     */
    private void updateOutExcepClosed(ExcpFormBO excpFormBO) {
        TmsOutboundInspectExcpExample excpExample = new TmsOutboundInspectExcpExample();
        excpExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpStatusEqualTo(ExcpStatusEnum.DEALING.getCode());
        int count = tmsOutboundInspectExcpMapper.countByExample(excpExample);
        if (count <= 0) {
            throw new BusinessException("非处理中异常不可关闭");
        }

        TmsOutboundInspectExcp outboundInspectExcp = new TmsOutboundInspectExcp();
        outboundInspectExcp.setGmtUpdate(new Date());
        outboundInspectExcp.setDealEndTime(new Date());
        outboundInspectExcp.setExcpStatus(ExcpStatusEnum.CLOSED.getCode());//更新状态已关闭
        outboundInspectExcp.setDealResultDesc(excpFormBO.getDealResultDesc());

        tmsOutboundInspectExcpMapper.updateByExampleSelective(outboundInspectExcp, excpExample);
    }

    /**
     * 更新入库的验车状态为30
     */
    private void updateStatusInbound(ExcpFormBO excpFormBO) {
        WmsInboundOrder updateOrder = new WmsInboundOrder();
        updateOrder.setGmtUpdate(new Date());
        updateOrder.setOdId(excpFormBO.getOrderId());
        updateOrder.setInspectStatus(TmsInspectStatusEnum.WAYBILL_EXCP.getValue());//验车状态
        wmsInboundOrderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    /**
     * 更新出库的验车状态为30
     */
    private void updateStatusOutbound(ExcpFormBO excpFormBO) {
        WmsOutboundTask updateTask = new WmsOutboundTask();
        updateTask.setGmtModify(new Date());
        updateTask.setOtId(excpFormBO.getOrderId());
        updateTask.setInspectStatus(TmsInspectStatusEnum.WAYBILL_EXCP.getValue());//验车状态
        wmsOutboundTaskMapper.updateByPrimaryKeySelective(updateTask);
    }

    /**
     * 判断入库维修单状态是否完成
     */
    private void queryCheckInboundepairStatus(ExcpFormBO excpFormBO) {
        TmsInspectExcpExample tmsInspectExcpExample = new TmsInspectExcpExample();
        tmsInspectExcpExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpTimestampEqualTo(excpFormBO.getExcpTimestamp());
        List<TmsInspectExcp> tmsInspectExcpList = tmsInspectExcpMapper.selectByExample(tmsInspectExcpExample);
        if (CollectionUtils.isNotEmpty(tmsInspectExcpList) && tmsInspectExcpList.get(0) != null) {
            //获取并判断维修单状态
            getAndCheckRepairStatus(tmsInspectExcpList.get(0).getExcpRepairId());
        }
    }

    /**
     * 判断入库维修单状态是否完成
     */
    private void queryCheckOutboundepairStatus(ExcpFormBO excpFormBO) {
        TmsOutboundInspectExcpExample tmsOutboundInspectExcpExample = new TmsOutboundInspectExcpExample();
        tmsOutboundInspectExcpExample.createCriteria()
                .andInspectIdEqualTo(excpFormBO.getOrderId())
                .andExcpTimestampEqualTo(excpFormBO.getExcpTimestamp());
        List<TmsOutboundInspectExcp> outboundInspectExcpList = tmsOutboundInspectExcpMapper.selectByExample(tmsOutboundInspectExcpExample);
        if (CollectionUtils.isNotEmpty(outboundInspectExcpList) && outboundInspectExcpList.get(0) != null) {
            //获取并判断维修单状态
            getAndCheckRepairStatus(outboundInspectExcpList.get(0).getExcpRepairId());
        }
    }

    /**
     * 获取并判断维修单状态
     */
    private void getAndCheckRepairStatus(Long repairId) {
        if (repairId != null) {
            WmsInboundRepair inboundRepair = wmsInboundRepairMapper.selectByPrimaryKey(repairId);
            if (inboundRepair == null) {
                throw new BusinessException("找不到对应的维修单信息");
            }
            if (!WmsInboundRepairStatusEnum.DEALED.getCode().equals(inboundRepair.getRpStatus())) {
                throw new BusinessException("对应的维修单未完成, 不可关闭异常");
            }
        }
    }

    /**
     * 封装维修单数据
     */
    private Long createRepair(ExcpFormBO excpFormBO, String inOutType, String inspectPlaceType) throws Exception {
        String materialNo = null;//物料代码
        String wayBillNo = null;//运单号
        String vehicleCode = null;//车型代码
        String vehicleName = null;//车型名字
        String vehicleDesc = null;//车型描述

        //获取运单号
        if (ExcepTypeEnum.IN_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
            //入库 - 物料代码
            WmsInboundOrderDetailExample detailExample = new WmsInboundOrderDetailExample();
            detailExample.createCriteria().andOddOdIdEqualTo(excpFormBO.getOrderId());
            List<WmsInboundOrderDetail> detailList = wmsInboundOrderDetailMapper.selectByExample(detailExample);
            if (CollectionUtils.isNotEmpty(detailList) && detailList.get(0) != null) {
                materialNo = detailList.get(0).getOddMaterialCode();
                vehicleCode = detailList.get(0).getOddVehicleSpecCode();
                vehicleName = detailList.get(0).getOddVehicleSpecName();
                vehicleDesc = detailList.get(0).getOddVehicleSpecDesc();
            }
            //入库 - 运单号
            WmsInboundOrder wmsInboundOrder = wmsInboundOrderMapper.selectByPrimaryKey(excpFormBO.getOrderId());
            if (wmsInboundOrder != null) {
                wayBillNo = wmsInboundOrder.getOdWaybillNo();
            }
        } else if (ExcepTypeEnum.OUT_EXCEP.getCode().equals(excpFormBO.getExcpType())) {
            //出库 - 物料代码
            WmsInventoryLocationExample locationExample = new WmsInventoryLocationExample();
            locationExample.createCriteria().andInvlocVinEqualTo(excpFormBO.getVin());
            List<WmsInventoryLocation> locationList = wmsInventoryLocationMapper.selectByExample(locationExample);
            if (CollectionUtils.isNotEmpty(locationList) && locationList.get(0) != null) {
                WmsInventory inventory = wmsInventoryMapper.selectByPrimaryKey(locationList.get(0).getInvlocInvId());
                if (inventory != null) {
                    materialNo = inventory.getInvMaterialCode();
                    vehicleCode = inventory.getInvVehicleSpecCode();
                    vehicleName = inventory.getInvVehicleSpecName();
                    vehicleDesc = inventory.getInvVehicleSpecDesc();
                }
            }
            //出库 - 运单号
            WmsOutboundTask outboundTask = wmsOutboundTaskMapper.selectByPrimaryKey(excpFormBO.getOrderId());
            if (outboundTask != null) {
                wayBillNo = outboundTask.getOtWaybillNo();
            }
        }
        return addRepair(excpFormBO.getVin(), excpFormBO.getExcpDesc(), excpFormBO.getDealType(), null,
                materialNo, excpFormBO.getWhCode(), wayBillNo, inOutType, inspectPlaceType, String.valueOf(excpFormBO.getOrderId()),
                vehicleCode, vehicleName, vehicleDesc);
    }

    /**
     * 生成维修单
     *
     * @param vin              车架号
     * @param excpDesc         异常类型
     * @param dealType         处理方式
     * @param invokeParty      责任方
     * @param materialNo       物料代码
     * @param whCode           仓库代码
     * @param wayBillNo        运单号
     * @param inOutType        出入库类型
     * @param inspectPlaceType 验车位置
     * @param orderId          订单ID
     * @param vehicleCode      车型代码
     * @param vehicleName      车型名称
     * @param vehicleDesc      车型描述
     */
    private Long addRepair(String vin, String excpDesc, String dealType, String invokeParty,
                           String materialNo, String whCode, String wayBillNo, String inOutType,
                           String inspectPlaceType, String orderId, String vehicleCode, String vehicleName, String vehicleDesc) throws Exception {
        WmsInboundRepair inboundRepair = new WmsInboundRepair();
        inboundRepair.setGmtCreate(new Date());
        inboundRepair.setRpVin(vin);//车架号
        inboundRepair.setRpStatus(WmsInboundRepairStatusEnum.NOT_DEAL.getCode());//维修状态
        //判断类型 - 是出库维修还是库内维修
        if (String.valueOf(ExcpDealTypeEnum.IN_WAREHOUSE_REPAIR.getCode()).equals(dealType)
                || String.valueOf(ExcpDealTypeEnum.MISS_FOLLOW_AND_IN_WAREHOUSE.getCode()).equals(dealType)) {
            //库内维修
            inboundRepair.setRpType(String.valueOf(WmsRepairTypeEnum.WMS_REPAIR_TYPE_INBOUND.getValue()));//维修单类型
        } else if (String.valueOf(ExcpDealTypeEnum.OUT_WAREHOUSE_REPAIR.getCode()).equals(dealType)
                || String.valueOf(ExcpDealTypeEnum.MISS_FOLLOW_AND_OUT_WAREHOUSE.getCode()).equals(dealType)) {
            //库外维修
            inboundRepair.setRpType(String.valueOf(WmsRepairTypeEnum.WMS_REPAIR_TYPE_OUTBOUND.getValue()));//维修单类型
        }
        inboundRepair.setRpProblemDescribe(excpDesc);//问题描述
        inboundRepair.setRpResponsibleParty(invokeParty);//责任方
        inboundRepair.setRpMaterialCode(materialNo);//物料编码
        inboundRepair.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        inboundRepair.setRpWhCode(whCode);
        inboundRepair.setRpWaybillNo(wayBillNo);//运单号
        inboundRepair.setRpInandoutType(inOutType);//出入库类型
        inboundRepair.setRepairInspectPlace(inspectPlaceType);//验车地点
        inboundRepair.setRpOdId(orderId);//订单ID
        inboundRepair.setRpVehicleSpecCode(vehicleCode);//车型代码
        inboundRepair.setRpVehicleSpecName(vehicleName);//车型代码
        inboundRepair.setRpVehicleSpecDesc(vehicleDesc);//车型描述
        wmsInboundRepairService.addInboundRepair(inboundRepair);
        return inboundRepair.getRpId();
    }

    /**
     * 分页请求参数的
     */
    private Map<String, Object> getParamMap(ExcpFormBO excpFormBO) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("limitStart", excpFormBO.getStartIndex());
        paramMap.put("limitEnd", excpFormBO.getPageSize());
        //异常分类
        if (StringUtils.isNotBlank(excpFormBO.getExcpType())) {
            paramMap.put("excpType", excpFormBO.getExcpType());
        }
        //异常类型
        if (StringUtils.isNotBlank(excpFormBO.getExcpTypeCode())) {
            paramMap.put("excpTypeCode", excpFormBO.getExcpTypeCode());
        }
        //异常状态
        if (StringUtils.isNotBlank(excpFormBO.getExcpStatus())) {
            paramMap.put("excpStatus", excpFormBO.getExcpStatus());
        } else {
            paramMap.put("excpStatus", ExcpStatusEnum.NOT_DEAL.getCode());
        }
        //处理方式
        if (StringUtils.isNotBlank(excpFormBO.getDealType())) {
            paramMap.put("dealType", excpFormBO.getDealType());
        }
        //异常发生时间
        if (StringUtils.isNotBlank(excpFormBO.getStartGmtCreate())) {
            //paramMap.put("startGmtCreate", DateUtils.StrToDate(excpFormBO.getStartGmtCreate(), DateUtils.YYYY_MM_DD));
            paramMap.put("startGmtCreate", excpFormBO.getStartGmtCreate() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(excpFormBO.getEndGmtCreate())) {
            //Date date = DateUtils.StrToDate(excpFormBO.getEndGmtCreate(), DateUtils.YYYY_MM_DD);
            //date.setTime(date.getTime() + 24 * 3600000 - 1);
            paramMap.put("endGmtCreate", excpFormBO.getEndGmtCreate() + " 23:59:59");
        }
        //处理完成时间
        if (StringUtils.isNotBlank(excpFormBO.getStartDealEndTime())) {
            //paramMap.put("startDealEndTime", DateUtils.StrToDate(excpFormBO.getStartDealEndTime(), DateUtils.YYYY_MM_DD));
            paramMap.put("startDealEndTime", excpFormBO.getStartDealEndTime() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(excpFormBO.getEndDealEndTime())) {
            //Date date = DateUtils.StrToDate(excpFormBO.getEndDealEndTime(), DateUtils.YYYY_MM_DD);
            //date.setTime(date.getTime() + 24 * 3600000 - 1);
            //paramMap.put("endDealEndTime", date);
            paramMap.put("endDealEndTime", excpFormBO.getEndDealEndTime() + " 23:59:59");

        }
        //根据订单号查询
        if (StringUtils.isNotBlank(excpFormBO.getOrderNo())) {
            paramMap.put("orderNo", excpFormBO.getOrderNo());
        }
        //根据车架号查询
        if (StringUtils.isNotBlank(excpFormBO.getVin())) {
            paramMap.put("vin", excpFormBO.getVin());
        }
        //设置验车人
        if (StringUtils.isNotBlank(excpFormBO.getInspectUserName())) {
            paramMap.put("inspectUserName", excpFormBO.getInspectUserName());
        }
        //paramMap.put("orderByClause", " ALL_TA.gmt_create desc");
        return paramMap;
    }

    /**
     * @param title       sheet标题
     * @param headers     表头
     * @param excpRecords 导出的异常列表
     * @param pattern     @Title exportExcel
     */
    private HSSFWorkbook updateExportToExcelForCQ(String title, String[] headers,
                                                  List<ExcpManageDTO> excpRecords, String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFCellStyle style2 = getHssfCellStyle(workbook, style);
        //// 声明一个画图的顶级管理器
        //HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        //// 定义注释的大小和位置,详见文档
        //HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
        //        0, 0, 0, (short) 4, 2, (short) 6, 5));
        //// 设置注释内容
        //comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
        //// 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
        //comment.setAuthor("leno");

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据，产生数据行
        Iterator<ExcpManageDTO> iterator = excpRecords.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            index++;
            row = sheet.createRow(index);//创建行
            ExcpManageDTO next = iterator.next();
            //对应头  设置cell的值
            for (short i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                switch (i) {
                    case 0: {
                        //"订单号"
                        cell.setCellValue(updateSetCellValue(next.getOrderNo()));
                        break;
                    }
                    case 1: {
                        //"车架号(VIN码)"
                        cell.setCellValue(updateSetCellValue(next.getVin()));
                        break;
                    }
                    case 2: {
                        // "异常分类"
                        if (StringUtils.isNotBlank(next.getExcpType())) {
                            WmsInspectExcpTypeEnum typeEnum = WmsInspectExcpTypeEnum.getByCode(next.getExcpType());
                            if (typeEnum != null) {
                                cell.setCellValue(updateSetCellValue(typeEnum.getName()));
                            }
                        }
                        break;
                    }
                    case 3: {
                        //"异常类型"
                        WmsInspectExcpTypeEnum codeEnum = WmsInspectExcpTypeEnum.getByCode(next.getExcpTypeCode());
                        if (codeEnum != null) {
                            cell.setCellValue(updateSetCellValue(codeEnum.getName()));
                        }
                        break;
                    }
                    case 4: {
                        //"异常状态"
                        if (StringUtils.isNotBlank(next.getExcpStatus())) {
                            ExcpStatusEnum dealStatus = ExcpStatusEnum.getByValue(Byte.valueOf(next.getExcpStatus()));
                            if (dealStatus != null) {
                                cell.setCellValue(updateSetCellValue(dealStatus.getText()));
                            }
                        }
                        break;
                    }
                    case 5: {
                        //"异常描述"
                        cell.setCellValue(updateSetCellValue(next.getExcpDesc()));
                        break;
                    }
                    //case 6: {
                    //    //"异常图片"
                    //    ExcpFormBO bo = new ExcpFormBO();
                    //    bo.setExcpType(next.getExcpType());
                    //    bo.setOrderId(next.getOrderId());
                    //    StringBuilder sb = new StringBuilder();
                    //    List<ExcpImageDTO> excpImageList = getExcpImageList(bo);
                    //    excpImageList.stream().filter(dto -> dto != null && StringUtils.isNotBlank(dto.getImageUrl()))
                    //            .forEach(v -> {
                    //                sb.append(v.getImageUrl()).append(",");
                    //            });
                    //    cell.setCellValue(updateSetCellValue(sb.toString().substring(0, sb.length() - 1)));
                    //    break;
                    //}
                    case 6: {
                        //"验车人"
                        cell.setCellValue(updateSetCellValue(next.getInspectUserName()));
                        break;
                    }
                    case 7: {
                        //"异常发生时间"
                        cell.setCellValue(getFormatDate(next.getGmtCreate()));
                        break;
                    }
                    case 8: {
                        //"处理方式"
                        if (StringUtils.isNotBlank(next.getDealType())) {
                            ExcpDealTypeEnum dealTypeEnum = ExcpDealTypeEnum.getByValue(Byte.parseByte(next.getDealType()));
                            if (dealTypeEnum != null) {
                                cell.setCellValue(updateSetCellValue(dealTypeEnum.getCode()));
                            }
                        }
                        break;
                    }
                    case 9: {
                        //"处理结果描述"
                        cell.setCellValue(updateSetCellValue(next.getDealResultDesc()));
                        break;
                    }
                    case 10: {
                        //"处理完成时间"
                        cell.setCellValue(updateSetCellValue(getFormatDate(next.getDealEndTime())));
                        break;
                    }
                    default:
                        break;
                }
            }
        }
        return workbook;
    }

    /**
     * 设置样式
     *
     * @param workbook 工作簿
     * @param style    样式
     * @return 返回值
     */
    private HSSFCellStyle getHssfCellStyle(HSSFWorkbook workbook, HSSFCellStyle style) {
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.WHITE.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        return style2;
    }

    /**
     * 判断字符串设置值--非空过滤
     *
     * @param object 传入参数
     * @return 返回值
     */
    private String updateSetCellValue(Object object) {
        if (!Objects.equals(object, null)) {
            String value = object.toString();
            if (StringUtils.isNotBlank(value)) {
                return value;
            }
        }
        return "";
    }

    /**
     * 时间格式化--非空过滤
     */
    private String getFormatDate(Date date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (date != null) {
            return sdf.format(date);
        }
        return "";
    }


}
